//
//  ROImagePickViewController.m
//  Runone
//
//  Created by runone02 on 16/12/29.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "ROImagePickViewController.h"
#import "ROImageBrowserController.h"
#import "ROImagePickerBottomBar.h"
#import "ROImagePickerFooterView.h"
#import "ROImageService.h"
#import "ROGroupView.h"
#import "ROAssetTittleView.h"
#import "UIButton+ROCameraPhotoes.h"
#import "ROImageCell.h"
#import "UIView+ROCameraPhotoes.h"

#define kBottomBarHeight  44.
#define SCREEN_W [UIScreen mainScreen].bounds.size.width
#define SCREEN_H [UIScreen mainScreen].bounds.size.height
static  NSString *kArtImagePickerCellIdentifier = @"ROImageCell";
static  NSString *kArtAssetsFooterViewIdentifier = @"ROImagePickFooterView";
#define kSizeThumbnailCollectionView  ([UIScreen mainScreen].bounds.size.width-10)/4
@interface ROImagePickViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,ROImageCellDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

//UI
@property (nonatomic, strong) UICollectionView           *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) ROGroupView                *assetGroupView;
@property (nonatomic, strong) ROImagePickerBottomBar     *bottomBar;
@property (nonatomic, strong) ROImagePickerFooterView    *footerView;
@property (nonatomic, strong) ROAssetTittleView          *groupTitleView;
@property (nonatomic, strong) UIView                     *overlayView;
@property (nonatomic, strong) UIButton                   *touchButton;

@property (nonatomic, strong) UIImagePickerController * currentPicker;

//Data
@property (nonatomic, strong) NSArray *assets;

@property (nonatomic, strong) NSMutableArray *selectAssets;

@end

@implementation ROImagePickViewController

- (void)showAssetsGroupView {
    [[UIApplication sharedApplication].keyWindow addSubview:self.touchButton];
    
    self.overlayView.alpha = 0.0f;
    [UIView animateWithDuration:0.3f
                     animations:^{
                         self.assetGroupView.originY = 0;
                         self.overlayView.alpha      = 0.85f;
                         self.groupTitleView.arrowBtn.transform = CGAffineTransformRotate(self.groupTitleView.arrowBtn.transform, M_PI);
                     }completion:^(BOOL finished) {
                         
                     }];
}

- (void)hideAssetsGroupView {
    [UIView animateWithDuration:0.3f
                     animations:^{
                         self.assetGroupView.originY = -self.assetGroupView.size.height;
                         self.overlayView.alpha = 0.0f;
                         self.groupTitleView.arrowBtn.transform = CGAffineTransformRotate(self.groupTitleView.arrowBtn.transform, M_PI);
                     }completion:^(BOOL finished) {
                         [_touchButton removeFromSuperview];
                         _touchButton = nil;
                         
                         [_overlayView removeFromSuperview];
                         _overlayView = nil;
                     }];
    
}

- (void)assetsGroupsDidDeselected {
    [self hideAssetsGroupView];
}

- (void)assetsGroupDidSelected {
    [self showAssetsGroupView];
}

- (void)groupViewDidSelected:(NSDictionary *)collection {
    // 获得某个相簿中的所有PHAsset对象
     __weak __typeof(self)weakSelf = self;
    [[ROImageService shared] fetchAssetsWithMediaType:ROPickerResourceTypeImage groupTitle:collection[kPHTitle] completion:^(NSString *title, NSArray *assets) {
        NSMutableArray *arrM = [NSMutableArray array];
        [arrM addObject:@"takephoto"];
        [arrM addObjectsFromArray:assets];
        weakSelf.assets = [arrM copy];
        dispatch_async(dispatch_get_main_queue(), ^{
            //先收起
            [weakSelf hideAssetsGroupView];
            //在更新数据
            [weakSelf.collectionView reloadData];
            //更新标题
            weakSelf.groupTitleView.titleButton.text = title;
            CGFloat width = [weakSelf.groupTitleView updateTitleConstraints];
            weakSelf.groupTitleView.frame = CGRectMake(0, 0, width, 40);
        });
    }];
}

- (void)back {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)addSelectAssets:(ROAsset *)asset {
 
    if (asset.isSelected) {
        [self.selectAssets addObject:asset];
    } else {
        [self.selectAssets removeObject:asset];
    }
    if (self.selectAssets.count == 0) {
        self.bottomBar.previewBtn.enabled = NO;
        self.bottomBar.sendBtn.enabled = NO;
        self.bottomBar.selectedCountBtn.hidden = YES;
    } else {
        self.bottomBar.previewBtn.enabled = YES;
        self.bottomBar.sendBtn.enabled = YES;
        self.bottomBar.selectedCountBtn.hidden = NO;
        [self.bottomBar.selectedCountBtn setTitle:[NSString stringWithFormat:@"%tu",self.selectAssets.count] forState:UIControlStateNormal];
    }
}

- (void)previewSelectAsset {
    //看大图
    ROImageBrowserController *browserVc = [[ROImageBrowserController alloc] init];
    
    __weak __typeof(self)weakSelf = self;
    browserVc.photoChooseBlock = ^(NSArray *assets){
        weakSelf.selectAssets = [assets mutableCopy];
    };
    
    browserVc.allAssets = self.selectAssets;
    browserVc.selectedAsset = self.selectAssets;
    browserVc.curIndex = 0;
    [self.navigationController pushViewController:browserVc animated:YES];
}

- (void)sendSelectAsset {
    
    if (self.photoChooseBlock) {
        self.photoChooseBlock(self.selectAssets);
        for (ROAsset *asset in self.selectAssets) {
            asset.selected = NO;
        }
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Load Data

- (void)fetchImagesInLibary {
    __weak __typeof(self)weakSelf = self;
    [[ROImageService shared] fectchAssetsWithMediaType:ROPickerResourceTypeImage  completion:^(NSString *title,NSArray *assets) {
        NSMutableArray *arrM = [NSMutableArray array];
        [arrM addObject:@"takephoto"];
        [arrM addObjectsFromArray:assets];
        weakSelf.assets = [arrM copy];
        weakSelf.groupTitleView.titleButton.text = title;
        CGFloat width = [weakSelf.groupTitleView updateTitleConstraints];
        self.groupTitleView.frame = CGRectMake(0, 0, width, 40);
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.collectionView reloadData];
        });
    }];
}

- (void)fetchPhotoLibaryCategory {
    //获取某一组的内容
    __weak __typeof(self)weakSelf = self;
    [[ROImageService shared] fetchImageGroupWithTypes:self.sourceType completion:^(NSArray *arr) {
        if (arr.count > 0) {
            weakSelf.assetGroupView.assetsGroups        = arr;
            weakSelf.groupTitleView.titleButton.enabled = YES;
        } else {
            weakSelf.groupTitleView.titleButton.enabled = NO;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.collectionView reloadData];
        });
    }];
}

- (void)askForAuthorize {
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        if (status == PHAuthorizationStatusAuthorized) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self buildUI];
                [self fetchPhotoLibaryCategory];
                [self fetchImagesInLibary];
            });
        }else{
            NSLog(@"Denied or Restricted");
            dispatch_async(dispatch_get_main_queue(), ^{
                [self buildRestrictedUI];
            });
        }
    }];
}

- (void)openAuthorization {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"相册权限未开启" message:@"相册权限未开启，请在设置中选择当前应用,开启相册功能" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *open = [UIAlertAction actionWithTitle:@"立即开启" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:open];
    [alert addAction:cancel];
    
    [self.navigationController presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark - Load View

- (void)buildUI {
    self.selectAssets = [NSMutableArray array];
    self.collectionView.frame = CGRectMake(0, 0, SCREEN_W, SCREEN_H - kBottomBarHeight);
    self.bottomBar.frame      = CGRectMake(0, SCREEN_H - kBottomBarHeight, SCREEN_W, kBottomBarHeight);
    [self.bottomBar.previewBtn addTarget:self action:@selector(previewSelectAsset) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomBar.sendBtn addTarget:self action:@selector(sendSelectAsset) forControlEvents:UIControlEventTouchUpInside];
    [self setUpProperties];
}

- (void)buildRestrictedUI {
    UIButton *tipBtn  = [UIButton buttonWithType:UIButtonTypeCustom];
    [tipBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    tipBtn.titleLabel.font          = [UIFont systemFontOfSize:13];
    tipBtn.titleLabel.numberOfLines = 2;
    tipBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [tipBtn setTitle:@"相册权限未开启，请在设置中选择当前应用,开启相册功能 \n 点击去设置" forState:UIControlStateNormal];
    tipBtn.frame           = CGRectMake(0, (SCREEN_H / 2.)-25, SCREEN_W, 50);
    tipBtn.backgroundColor = [UIColor greenColor];
    [self.view addSubview:tipBtn];
    [self.view bringSubviewToFront:tipBtn];
    [tipBtn addTarget:self action:@selector(openAuthorization) forControlEvents:UIControlEventTouchUpInside];
}



- (void)setUpProperties {
    self.navigationItem.titleView = self.groupTitleView;
    CGFloat width                 = [self.groupTitleView updateTitleConstraints];
    self.groupTitleView.frame     = CGRectMake(0, 0, width, 40);
    __weak __typeof(self)weakSelf = self;
    self.groupTitleView.titleViewDidClick = ^{
        [weakSelf assetsGroupDidSelected];
    };
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
}

#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self askForAuthorize];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshCollectionVIew) name:@"refreshCollection" object:nil];
}

- (void) refreshCollectionVIew {
    [self fetchPhotoLibaryCategory];
    [self fetchImagesInLibary];
    [_currentPicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self askForAuthorize];
    [self.collectionView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    NSLog(@"%s",__func__);
}

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.assets.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ROAsset *asset    = self.assets[indexPath.item];
    ROImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kArtImagePickerCellIdentifier forIndexPath:indexPath];
    cell.delegate = self;
    [cell configImageCell:asset];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *reusableView = nil;
    
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        self.footerView = (ROImagePickerFooterView *)[collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                                         withReuseIdentifier:kArtAssetsFooterViewIdentifier
                                                                                                forIndexPath:indexPath];
        if (self.sourceType == ROPickerResourceTypeImage) {
            [self.footerView configFooterViewImageCount:0 videoCount:self.assets.count updateTime:nil];
        } else {
            [self.footerView configFooterViewImageCount:self.assets.count videoCount:0 updateTime:nil];
        }
        reusableView = self.footerView;
    } else if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
    }
    
    return reusableView;
}

#pragma mark- UIImagePickerViewController
//UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);  
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSLog(@"%@",info);
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
//    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
//        
//        //写入图片到相册
//        PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
//        
//        
//    } completionHandler:^(BOOL success, NSError * _Nullable error) {
//        
//        NSLog(@"success = %d, error = %@", success, error);
//        dispatch_async(dispatch_get_main_queue(), ^{
//           
//            if (success) {
//                
//                [picker dismissViewControllerAnimated:NO completion:^{
//                    [self fetchPhotoLibaryCategory];
//                    [self fetchImagesInLibary];
//                }];
//            }
//           
//        });
//        
//    }];
    
    
    
    _currentPicker = picker;
//    当image从相机中获取的时候存入相册中
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(image,self,@selector(image:didFinishSavingWithError:contextInfo:),NULL);

    }
}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo  {
    if (!error) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshCollection" object:nil];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - ROImageCellDelegate

- (void)imageDidSelect:(ROAsset *)asset select:(BOOL)isSelect {
    [self addSelectAssets:asset];
}

- (void)imageDidTapped:(ROAsset *)asset select:(BOOL)isSelect {
    if ([asset isKindOfClass:[NSString class]]) {
        //拍照
        UIImagePickerController *pickerController = [[UIImagePickerController alloc]init];
        pickerController.allowsEditing = NO;
        pickerController.delegate      = self;
        pickerController.sourceType    = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:pickerController animated:YES completion:nil];
        
    } else if ([asset isKindOfClass:[ROAsset class]]) {
        //看大图
        ROImageBrowserController *browserVc = [[ROImageBrowserController alloc] init];
        __weak __typeof(self)weakSelf = self;
        browserVc.photoChooseBlock = ^(NSArray *assets){
            weakSelf.selectAssets = [assets mutableCopy];
            if (weakSelf.selectAssets.count > 0) {
                weakSelf.bottomBar.previewBtn.enabled = YES;
                weakSelf.bottomBar.sendBtn.enabled    = YES;
                [weakSelf.bottomBar.selectedCountBtn setSelected:YES];
                weakSelf.bottomBar.selectedCountBtn.hidden = NO;
                [weakSelf.bottomBar.selectedCountBtn setTitle:[NSString stringWithFormat:@"%tu",weakSelf.selectAssets.count] forState:UIControlStateSelected];
            } else {
                weakSelf.bottomBar.previewBtn.enabled = NO;
                weakSelf.bottomBar.sendBtn.enabled = NO;
                [weakSelf.bottomBar.selectedCountBtn setSelected:NO];
                weakSelf.bottomBar.selectedCountBtn.hidden = YES;
            }
            [weakSelf.bottomBar.selectedCountBtn setTitle:[NSString stringWithFormat:@"%tu",weakSelf.selectAssets.count] forState:UIControlStateNormal];
            [weakSelf.collectionView reloadData];
        };
        
        browserVc.allAssets = [NSMutableArray arrayWithArray:self.assets];
        browserVc.selectedAsset = self.selectAssets;
        browserVc.curIndex = [self.assets indexOfObject:asset];
        [self.navigationController pushViewController:browserVc animated:YES];
    }
}

#pragma mark - Lazy Load

- (UICollectionView *)collectionView {
    if (_collectionView == nil) {
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        [_collectionView registerClass:[ROImageCell class] forCellWithReuseIdentifier:kArtImagePickerCellIdentifier];
        [_collectionView registerClass:[ROImagePickerFooterView class]
            forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                   withReuseIdentifier:kArtAssetsFooterViewIdentifier];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_collectionView];
        
    }
    return _collectionView;
}

- (UICollectionViewFlowLayout *)layout {
    if (_layout == nil) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.minimumLineSpacing = 2.0;
        _layout.minimumInteritemSpacing = 2.0;
        _layout.itemSize = CGSizeMake(kSizeThumbnailCollectionView, kSizeThumbnailCollectionView);
        _layout.sectionInset = UIEdgeInsetsMake(2, 2, 2, 2);
        _layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _layout.footerReferenceSize = CGSizeMake(SCREEN_W, 65);  //设置footer大小
    }
    return _layout;
}

- (ROGroupView *)assetGroupView {
    if (_assetGroupView == nil) {
        _assetGroupView = [[ROGroupView alloc] initWithFrame:CGRectMake(0, -self.view.size.height, self.view.size.width, self.view.size.height)];
        _assetGroupView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        [_assetGroupView.touchButton addTarget:self action:@selector(hideAssetsGroupView) forControlEvents:UIControlEventTouchUpInside];
        __weak __typeof(self)weakSelf = self;
        _assetGroupView.groupSelectedBlock = ^(NSDictionary *collection){
            [weakSelf groupViewDidSelected:collection];
        };
        [self.view addSubview:_assetGroupView];
        
    }
    return _assetGroupView;
}

- (UIView *)overlayView{
    if (!_overlayView) {
        _overlayView = [[UIView alloc] initWithFrame:self.view.bounds];
        _overlayView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.85f];
        [self.view insertSubview:_overlayView belowSubview:self.assetGroupView];
        
    }
    return _overlayView;
}

- (UIButton *)touchButton {
    if (!_touchButton) {
        _touchButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _touchButton.frame = CGRectMake(0, 0, self.view.size.width, 64);
        [_touchButton setBackgroundColor:[UIColor clearColor]];
        [_touchButton addTarget:self action:@selector(assetsGroupsDidDeselected) forControlEvents:UIControlEventTouchUpInside];
    }
    return _touchButton;
}

- (ROAssetTittleView *)groupTitleView {
    if (_groupTitleView == nil) {
        _groupTitleView = [[ROAssetTittleView alloc] init];
    }
    return _groupTitleView;
}

- (ROImagePickerBottomBar *)bottomBar {
    if (_bottomBar == nil) {
        _bottomBar = [[ROImagePickerBottomBar alloc] init];
        [self.view addSubview:_bottomBar];
    }
    return _bottomBar;
}


@end
